package com.example.tongue.ui.Seetongue;

import static android.content.ContentValues.TAG;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.tongue.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Camera extends Activity implements View .OnClickListener{
    private ImageView seePicture;
    private Button savePicture, photograph;
    private Uri imageUri;
    public static final int TAKE_PHOTO = 1;//请求码>=0即可


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carmera);
        //控件绑定资源
        savePicture = findViewById(R.id.SavePicture);
        seePicture = findViewById(R.id.SeePicture);
        photograph =findViewById(R.id.Photograph);
        //为按钮设置监听器
        photograph.setOnClickListener(this);
        savePicture.setOnClickListener(this);
    }


//摄像界面关闭后返回照片数据
//第一个参数为请求码，即调用startActivityForResult()传递过去的值
//第二个参数为结果码，结果码用于标识返回数据来自哪个子Activity
//requestCode<0时,退出活动不进入该函数
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

                try {        // 将图片解析成Bitmap对象
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        seePicture.setImageBitmap(bitmap);//展示图片
                        System.out.println(data);
                        System.out.println("==================================");
                        Toast.makeText(Camera.this,"退出相机界面",Toast.LENGTH_SHORT).show();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.Photograph:{

                // 创建一个File对象，用于保存摄像头拍下的图片，这里把图片命名为output_image.jpg
                // 并将它存放在手机SD卡的应用关联缓存目录下
                //1.新建目录
                String path=getExternalCacheDir()+"/TongueImage";
                System.out.println(getExternalCacheDir());

                File outputImageDir = new File(path);
                if(outputImageDir.exists()){
                    outputImageDir.delete();
                    outputImageDir.mkdir();
                }else{
                    outputImageDir.mkdir();
                }
                //新建文件
                File outputImage=new File(path,"CacheImage.jpg");
                // 对照片的更换设置
                try {
                    // 如果上一次的照片存在，就删除
                    if (outputImage.exists()) {
                        outputImage.delete();
                    }
                    // 创建一个新的文件
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 如果Android版本大于等于7.0
                if (Build.VERSION.SDK_INT >= 24) {
                    // 将File对象转换成一个封装过的Uri对象
                    imageUri = FileProvider.getUriForFile(Camera.this, "com.example.tongue.fileprovider", outputImage);
//                    Log.d("MainActivity", outputImage.toString() + "手机系统版本高于Android7.0");
                } else {
                    // 将File对象转换为Uri对象，这个Uri标识着output_image.jpg这张图片的本地真实路径
//                    Log.d("MainActivity", outputImage.toString() + "手机系统版本低于Android7.0");
                    imageUri = Uri.fromFile(outputImage);
                }
                // 动态申请权限
                if (ContextCompat.checkSelfPermission(Camera.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Camera.this,new String[]{Manifest.permission.CAMERA}, TAKE_PHOTO);
                } else {
                    // 启动相机程序
                    startCamera();
                }

            }
            break;
            case R.id.SavePicture:{
                BitmapDrawable bmpDrawable = (BitmapDrawable) seePicture.getDrawable();
                Bitmap bitmap = bmpDrawable.getBitmap();
                saveToSystemGallery(bitmap);//将图片保存到本地
                Toast.makeText(getApplicationContext(),"图片保存成功！",Toast.LENGTH_SHORT).show();

            }
            break;
        }

    }

    private void startCamera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 指定图片的输出地址为imageUri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        //在当前活动中打开新的子活动--->相机
        startActivityForResult(intent, TAKE_PHOTO);
    }
    public void saveToSystemGallery(Bitmap bmp) {
        // 将临时文件写入内存永久性保存
        File appDir = new File(Environment.getExternalStorageDirectory(), "TongueImage");
        System.out.println(Environment.getExternalStorageDirectory());
//        Log.d(TAG, "saveToSystemGallery:"+Environment.getExternalStorageDirectory());
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);// 发送广播，通知图库更新
    }



}
